<template>
  <div class="login-view">
    <el-card class="login-card">
      <template #header>
        <h2 class="login-title">用户登录</h2>
      </template>

      <el-form :model="loginForm" :rules="rules" ref="loginFormRef">
        <el-form-item prop="name">
          <el-input
            v-model="loginForm.name"
            placeholder="请输入用户名"
            :prefix-icon="User"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <el-form-item prop="userType">
          <el-radio-group v-model="loginForm.userType">
            <el-radio :label="0">普通用户</el-radio>
            <el-radio :label="1">交管部门</el-radio>
            <el-radio :label="2">管理员</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <div class="button-group">
            <el-button type="primary" @click="handleLogin" class="login-button">
              登录
            </el-button>
            <el-button @click="goToRegister" class="register-button">
              前往注册
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import request from '../utils/request'
import { useMainStore } from '../../stores/index'

const store = useMainStore()
const router = useRouter()

const loginForm = reactive({
  name: '',
  password: '',
  userType: 0, // 0: 普通用户, 1: 交管部门, 2: 管理员
})

const rules = {
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    {
      min: 3,
      max: 20,
      message: '用户名长度应在3-20个字符之间',
      trigger: 'blur',
    },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应在6-20个字符之间', trigger: 'blur' },
  ],
}

const loginFormRef = ref(null)

const handleLogin = async () => {
  try {
    // 统一接口
    const endpoint = '/commonUsers/login'
    const params = {
      name: loginForm.name,
      password: loginForm.password,
    }
    const res = await request.post(endpoint, params)
    if (res.code === 200) {
      // 保存token（如有）
      if (res.token) store.setToken(res.token)
      // 保存用户信息
      store.setUser(res.user)
      // 跳转
      if (res.user?.juri === 0) {
        router.push({ name: 'usermap' })
      } else if (res.user?.juri === 1) {
        router.push({ name: 'traffic' })
      } else if (res.user?.juri === 2) {
        router.push({ name: 'admin' })
      } else {
        ElMessage.error('未知用户类型')
        return
      }
      ElMessage.success(res.message || '登录成功')
    } else {
      ElMessage.error(res.message || '登录失败')
    }
  } catch (error) {
    console.error('登录错误:', error)
    ElMessage.error('登录失败，请检查网络连接')
  }
}

const goToRegister = () => {
  router.push({ name: 'register' })
}
</script>

<style lang="scss" scoped>
.login-view {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;

  .login-card {
    width: 400px;

    .login-title {
      text-align: center;
      margin: 0;
      color: #303133;
    }

    .button-group {
      display: flex;
      gap: 20px;
      margin-top: 10px;
      width: 100%;

      .login-button,
      .register-button {
        flex: 1;
        height: 40px;
        font-size: 15px;
        border-radius: 4px;
        transition: all 0.3s ease;
      }

      .login-button {
        background: linear-gradient(to right, #409eff, #3a8ee6);
        border: none;
      }

      .register-button {
        background-color: #fff;
        border: 1px solid #dcdfe6;
        color: #606266;
      }
    }

    .el-radio-group {
      width: 100%;
      display: flex;
      justify-content: space-around;
    }
  }
}
</style>
